package com.alibaba.citrus.ots.platform.enhance.repository.impl;

import com.alibaba.acm.shaded.com.alibaba.metrics.StringUtils;
import com.alibaba.citrus.ots.common.exception.FacadeException;
import com.alibaba.citrus.ots.platform.enhance.repository.CustomerRepository;
import com.alibaba.citrus.ots.platform.enhance.repository.CustomerSaleScopeRepository;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.*;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.otsplatformenhance.api.customersalescopequery.dto.BatchQueryCustomerSaleScopeRequest;
import com.epoch.app.otsplatformenhance.channel.service.ChannelService;
import com.epoch.app.otsplatformenhance.domain.customer.dto.CustomerLoadListRequest;
import com.epoch.app.otsplatformenhance.domain.customer.model.Customer;
import com.epoch.app.otsplatformenhance.domain.customer.service.CustomerService;
import com.epoch.app.otsplatformenhance.domain.customersalescope.dto.*;
import com.epoch.app.otsplatformenhance.domain.customersalescope.model.CustomerSaleScope;
import com.epoch.app.otsplatformenhance.domain.customersalescope.service.CustomerSaleScopeService;
import com.epoch.app.otsplatformenhance.domain.scitemgroup.dto.LoadScItemGroupListRequest;
import com.epoch.app.otsplatformenhance.domain.scitemgroup.model.ScItemGroup;
import com.epoch.app.otsplatformenhance.domain.scitemgroup.service.ScItemGroupService;
import com.epoch.app.otsplatformenhance.dto.request.CustomerBatchRequest;
import com.epoch.app.otsplatformenhance.dto.request.QuerySaleScopeRequest;
import com.epoch.app.otsplatformenhance.model.dto.ChannelResponse;
import com.epoch.app.otsplatformenhance.model.dto.QueryChannelRequest;
import com.epoch.app.otsplatformenhance.opecustomerindex.dto.PageQueryCustomerRequest;
import com.epoch.app.otsplatformenhance.opecustomerindex.dto.PageQueryCustomerResponse;
import com.epoch.app.otsplatformenhance.opecustomerindex.service.OpeCustomerIndexService;
import com.epoch.app.otsplatformenhance.sdo.CustomerSDO;
import com.epoch.app.otsplatformenhance.sdo.CustomerSaleScopeSDO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class CustomerSaleScopeRepositoryImpl implements CustomerSaleScopeRepository {
    private static final Log log = Log.getLogger(CustomerSaleScopeRepositoryImpl.class);

    @Resource
    private CustomerSaleScopeService service;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private ScItemGroupService scItemGroupService;

    @Resource
    private ChannelService channelService;

    @Resource
    private CustomerRepository customerRepository;

    @Resource
    private CustomerService customerService;


    @Override
    public Boolean edit(CustomerSaleScopeSDO saleScopeSDO) {
        log.info("CustomerSaleScopeRepositoryImpl.edit接口入参" + JSONObject.toJSONString(saleScopeSDO));
        CustomerSaleScope updateRequest = new CustomerSaleScope();
        BeanUtils.copyProperties(saleScopeSDO, updateRequest);
        Set<String> platform = new HashSet<>();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(saleScopeSDO.getCommercePlatform())) {
            List<PlatformSDO> queryPlatforms1 = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformIds(Lists.newArrayList(saleScopeSDO.getCommercePlatform())).build()).getResult();
            if (CollectionUtils.isNotEmpty(queryPlatforms1)) {
                for (PlatformSDO platformSDO : queryPlatforms1) {
                    platform.add(platformSDO.getPlatformName());
                }
            }
            //判断传入的是否是页面回显的中文
            if (platform.contains(saleScopeSDO.getCommercePlatform())) {
                List<PlatformSDO> queryPlatforms2 = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformNames(Lists.newArrayList(saleScopeSDO.getCommercePlatform())).build()).getResult();
                String platformCode1 = queryPlatforms2.get(0).getPlatformCode();
                updateRequest.setCommercePlatform(platformCode1);
            } else {
                //如果不包含说明传入的重选的id  那么就根据id去查询就可以
                List<PlatformSDO> queryPlatforms3 = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformIds(Lists.newArrayList(saleScopeSDO.getCommercePlatform())).build()).getResult();
                String platformCode2 = queryPlatforms3.get(0).getPlatformCode();
                updateRequest.setCommercePlatform(platformCode2);
            }
        } else {
            //如果在编辑的时候 把电商平台去除了 那么就滞空进行修改
            updateRequest.setCommercePlatform("");
        }
        //如果在分派或导入时  负责人为空 则置为空值 进行修改
        if (org.apache.commons.lang3.StringUtils.isBlank(saleScopeSDO.getPrincipal())) {
            updateRequest.setPrincipal("");
        }
        if (StringUtils.isNotBlank(saleScopeSDO.getCommercePlatformCode())) {
            updateRequest.setCommercePlatform(saleScopeSDO.getCommercePlatformCode());
        }
        updateRequest.setId(Long.parseLong(saleScopeSDO.getId()));
        updateRequest.setUpdater(saleScopeSDO.getUpdater());
        updateRequest.setGmtModified(new Date());
        Integer count = 0;
        try {
            log.info("CustomerSaleScopeRepositoryImpl.update入参" + JSONObject.toJSONString(updateRequest));
            UpdateCustomerSaleScopeResponse response = service.updateCustomerSaleScope(updateRequest);
            count = response.getCount();
            log.info("CustomerSaleScopeRepositoryImpl.update返回值:" + count);
            if (count == 0) {
                return false;
            }
        } catch (Exception e) {
            throw new RuntimeException("数据更新失败");
        }
        log.info("CustomerSaleScopeRepositoryImpl.edit成功");
        return true;
    }

    @Override
    public List<CustomerSaleScopeSDO> queryList(CustomerSaleScopeSDO customerSaleScopeSDO) {
        CustomerSaleScopeLoadListRequest loadListRequest = new CustomerSaleScopeLoadListRequest();
        BeanUtils.copyProperties(customerSaleScopeSDO, loadListRequest);
        loadListRequest.setDir("gmt_create");
        Result<List<CustomerSaleScope>> saleScopeResult = service.loadCustomerSaleScopeList(loadListRequest);
        //  List<CustomerSaleScopeSDO> resultList = new ArrayList<>();
        List<CustomerSaleScopeSDO> resultList = saleScopeResult.getResult().stream().map(saleScope -> {
            CustomerSaleScopeSDO saleScopeSDO = new CustomerSaleScopeSDO();
            BeanUtils.copyProperties(saleScope, saleScopeSDO);
            saleScopeSDO.setId(saleScope.getId().toString());
            JSONObject jsonobject = JSONObject.parseObject(saleScope.getFeatures());
            String itemGroupName = (String) jsonobject.get("itemGroupName");
            saleScopeSDO.setItemGroupName(itemGroupName);
            return saleScopeSDO;
        }).collect(Collectors.toList());

//        for (CustomerSaleScope saleScope : saleScopeResult.getResult()) {
//            CustomerSaleScopeSDO saleScopeSDO = new CustomerSaleScopeSDO();
//            BeanUtils.copyProperties(saleScope, saleScopeSDO);
//            saleScopeSDO.setId(saleScope.getId().toString());
//            resultList.add(saleScopeSDO);
//        }
        return resultList;
    }

    private CustomerSaleScopeLoadListRequest loadCodeRequestConverter(CustomerSaleScopeSDO saleScopeSDO) {
        CustomerSaleScopeLoadListRequest loadListRequest = new CustomerSaleScopeLoadListRequest();
        BeanUtils.copyProperties(saleScopeSDO, loadListRequest);
        return loadListRequest;
    }

    @Override
    public PageResult<List<CustomerSaleScopeSDO>> pageQuery(QuerySaleScopeRequest request) {
        log.error("CustomerSaleScopeRepositoryImpl.pageQuery入参:" + JSONObject.toJSONString(request));
        LoadCustomerSaleScopeList2Request loadListRequest = new LoadCustomerSaleScopeList2Request();
        BeanUtils.copyProperties(request, loadListRequest);
        if (StringUtils.isNotBlank(request.getCustomerName())) {
            Result<List<Customer>> listResult = customerService.loadCustomerList(CustomerLoadListRequest.newCustomerLoadListRequestBuilder().name(request.getCustomerName()).build());
            if (CollectionUtils.isNotEmpty(listResult.getResult())) {
                List<String> customerCodes = listResult.getResult().stream().map(Customer::getCode).collect(Collectors.toList());
                loadListRequest.setCustomerCodeList(customerCodes);
            }
        }
        if (StringUtils.isNotBlank(request.getId())) {
            loadListRequest.setId(Long.valueOf(request.getId()));
        }
        if (StringUtils.isNotBlank(request.getCustomerCode1())) {
            loadListRequest.setCustomerCode(request.getCustomerCode1());
        }
        if (CollectionUtils.isNotEmpty(request.getOrgSaleChannelCodeList())) {
            loadListRequest.setOrgSaleChannelCodeList(request.getOrgSaleChannelCodeList());
        }
        if (CollectionUtils.isNotEmpty(request.getOrgSaleDepartmentCodeList())) {
            loadListRequest.setOrgSaleDepartmentCodeList(request.getOrgSaleDepartmentCodeList());
        }
        if (CollectionUtils.isNotEmpty(request.getCommercePlatformList())) {
            loadListRequest.setCommercePlatformList(request.getCommercePlatformList());
        }
        if (StringUtils.isNotBlank(request.getCommercePlatform())) {
            List<PlatformSDO> result = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformIds(Lists.newArrayList(request.getCommercePlatform())).build()).getResult();
            if (CollectionUtils.isNotEmpty(result)) {
                for (PlatformSDO platformSDO : result) {
                    loadListRequest.setCommercePlatform(platformSDO.getPlatformCode());
                }
            }
        }
        loadListRequest.setDir("gmt_create");

        //获取销售组织、销售渠道、销售部门
        log.error("CustomerSaleScopeRepositoryImpl.pageQuery.loadCustomerSaleScopeList2查询入参:" + JSONObject.toJSONString(loadListRequest));
        Result<List<CustomerSaleScope>> saleScopeResult = service.loadCustomerSaleScopeList2(loadListRequest);
        log.error("CustomerSaleScopeRepositoryImpl.pageQuery.saleScopeResult查询结果为:" + JSONObject.toJSONString(saleScopeResult));
        Set<String> business = saleScopeResult.getResult().stream().map(CustomerSaleScope::getOrgSaleOrganizationCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> saleChannel = saleScopeResult.getResult().stream().map(CustomerSaleScope::getOrgSaleChannelCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> depart = saleScopeResult.getResult().stream().map(CustomerSaleScope::getOrgSaleDepartmentCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> codes = Sets.newHashSet();
        Set<String> customerCodes = saleScopeResult.getResult().stream().map(CustomerSaleScope::getCustomerCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        codes.addAll(business);
        codes.addAll(saleChannel);
        codes.addAll(depart);
        CustomerBatchRequest batchRequest = CustomerBatchRequest.builder().codes(Lists.newArrayList(customerCodes)).build();
        List<CustomerSDO> customerSDOS = customerRepository.batchQuery(batchRequest);
        log.error("CustomerSaleScopeRepositoryImpl.customerRepository.batchQuery入参为:" + JSONObject.toJSONString(batchRequest));
        Map<String, CustomerSDO> customerSDOMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(customerSDOS)) {
            customerSDOMap = customerSDOS.stream().collect(Collectors.toMap(CustomerSDO::getCode, o -> o));
        }
        BaselineGetOrganizationByIds2Request byIds2Request = new BaselineGetOrganizationByIds2Request();
        byIds2Request.setIds(Lists.newArrayList(codes));
        byIds2Request.setStatus(1);
        BaselineGetOrganizationByIds2Response byIds2Response = baseDataService.baselineGetOrganizationByIds2(byIds2Request);
        log.error("CustomerSaleScopeRepositoryImpl.baseDataService.baselineGetOrganizationByIds2入参为:" + JSONObject.toJSONString(byIds2Request));
        if (byIds2Response == null || CollectionUtils.isEmpty(byIds2Response.getResult())) {
            return new PageResult<List<CustomerSaleScopeSDO>>();
        }
        Map<String, OrganizationSDO> organizationSDOMap = byIds2Response.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, o -> o));

        Map<String, CustomerSDO> finalCustomerSDOMap = customerSDOMap;
        List<CustomerSaleScopeSDO> resultList = saleScopeResult.getResult().stream().map(saleScope -> {
            String channelName = "";
            String itemGroupName = "";
            String salesAreaName = "";
            String transportAreaName = "";
            String customerName = "";
            String transportArea = "";
            String outOrgSalesDepartmentCode = "";
            String outOrgSalesDepartmentName = "";
            String outOrgSalesChannelCode = "";
            String outOrgSalesChannelName = "";
            String storeHouse = "";
            CustomerSaleScopeSDO saleScopeSDO = new CustomerSaleScopeSDO();
            BeanUtils.copyProperties(saleScope, saleScopeSDO);
            if (StringUtil.isNotEmpty(saleScope.getFeatures())) {
                JSONObject jsonobject = JSONObject.parseObject(saleScope.getFeatures());
                channelName = jsonobject.getString("channelName");
                itemGroupName = jsonobject.getString("itemGroupName");
                salesAreaName = jsonobject.getString("salesAreaName");
                transportAreaName = jsonobject.getString("transportAreaName");
                customerName = jsonobject.getString("customerName");
                transportArea = jsonobject.getString("transportArea");
                outOrgSalesDepartmentCode = jsonobject.getString("outOrgSalesDepartmentCode");
                outOrgSalesDepartmentName = jsonobject.getString("outOrgSalesDepartmentName");
                outOrgSalesChannelCode = jsonobject.getString("outOrgSalesChannelCode");
                outOrgSalesChannelName = jsonobject.getString("outOrgSalesChannelName");
                storeHouse = jsonobject.getString("storeHouse");
                saleScopeSDO.setItemGroupName(itemGroupName);
                saleScopeSDO.setChannelName(channelName);
                saleScopeSDO.setSalesAreaName(salesAreaName);
                saleScopeSDO.setTransportAreaName(transportAreaName);
                saleScopeSDO.setCustomerName(customerName);
                saleScopeSDO.setTransportArea(transportArea);
                saleScopeSDO.setOutOrgSalesDepartmentCode(outOrgSalesDepartmentCode);
                saleScopeSDO.setOutOrgSalesDepartmentName(outOrgSalesDepartmentName);
                saleScopeSDO.setOutOrgSalesChannelCode(outOrgSalesChannelCode);
                saleScopeSDO.setOutOrgSalesChannelName(outOrgSalesChannelName);
                saleScopeSDO.setStoreHouse(storeHouse);
            }

            //客户名称
            CustomerSDO customerSDO = finalCustomerSDOMap.get(saleScope.getCustomerCode());
            if (Objects.nonNull(customerSDO)) {
                saleScopeSDO.setCustomerName(customerSDO.getName());
            }
            //货品组名称
            LoadScItemGroupListRequest itemGroupListRequest = LoadScItemGroupListRequest.builder().code(saleScope.getItemGroup()).build();
            Result<List<ScItemGroup>> result = scItemGroupService.loadScItemGroupList(itemGroupListRequest);
            if (Objects.nonNull(result) || CollectionUtils.isNotEmpty(result.getResult())) {
                ScItemGroup scItemGroup = result.getResult().stream().findFirst().get();
                saleScopeSDO.setItemGroupName(scItemGroup.getName());
            }
            QueryChannelRequest channelRequest = QueryChannelRequest.builder().channelCode(saleScope.getChannelCode()).build();

            //渠道名称
            Result<ChannelResponse> responseResult = channelService.queryChannelDetail(channelRequest);
            if (Objects.nonNull(responseResult) && Objects.nonNull(responseResult.getResult())) {
                ChannelResponse channelResponse = responseResult.getResult();
                saleScopeSDO.setChannelName(channelResponse.getChannelName());
            }
            //组织名称
            if (organizationSDOMap.get(saleScope.getOrgSaleOrganizationCode()) != null) {
                OrganizationSDO sdo = organizationSDOMap.get(saleScope.getOrgSaleOrganizationCode());
                saleScopeSDO.setOrgSalesOrganizationName(sdo.getName());
            }
            if (organizationSDOMap.get(saleScope.getOrgSaleChannelCode()) != null) {
                OrganizationSDO sdo = organizationSDOMap.get(saleScope.getOrgSaleChannelCode());
                saleScopeSDO.setOrgSalesChannelName(sdo.getName());
            }
            if (organizationSDOMap.get(saleScope.getOrgSaleDepartmentCode()) != null) {
                OrganizationSDO sdo = organizationSDOMap.get(saleScope.getOrgSaleDepartmentCode());
                saleScopeSDO.setOrgSalesDepartmentName(sdo.getName());
            }
            saleScopeSDO.setId(saleScope.getId().toString());
            //电商平台
            queryCommercePlatform(saleScopeSDO);
            return saleScopeSDO;
        }).collect(Collectors.toList());

        return PageResult.of(resultList, saleScopeResult.getTotal());
    }

    private void queryCommercePlatform(CustomerSaleScopeSDO saleScopeSDO) {
        //根据当前数据的平台Code去获取对应的名称
        if (org.apache.commons.lang3.StringUtils.isNotBlank(saleScopeSDO.getCommercePlatform())) {
            List<PlatformSDO> platformSDOS = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformCodes(Lists.newArrayList(saleScopeSDO.getCommercePlatform())).build()).getResult();
            log.error("CustomerSaleScopeRepositoryImpl.queryCommercePlatform查询结果为:" + JSONObject.toJSONString(platformSDOS));
            if (CollectionUtils.isNotEmpty(platformSDOS)) {
                String platformName = platformSDOS.get(0).getPlatformName();
                String platformCode = platformSDOS.get(0).getPlatformCode();
                saleScopeSDO.setCommercePlatform(platformName);
                saleScopeSDO.setCommercePlatformCode(platformCode);
            }
        }
    }

    @Override
    public CustomerSaleScopeSDO load(String id) {
        LoadCustomerSaleScopeRequest loadRequest = new LoadCustomerSaleScopeRequest();
        loadRequest.setId(id);
        CustomerSaleScope customerSaleScope = new CustomerSaleScope();
        try {
            customerSaleScope = service.loadCustomerSaleScope(loadRequest);
        } catch (Exception e) {
            return null;
        }
        CustomerSaleScopeSDO saleScopeSDO = new CustomerSaleScopeSDO();
        BeanUtils.copyProperties(customerSaleScope, saleScopeSDO);
        saleScopeSDO.setId(String.valueOf(customerSaleScope.getId()));
        return saleScopeSDO;
    }

    @Override
    public List<CustomerSaleScopeSDO> batchQueryCustomerSaleSCope(BatchQueryCustomerSaleScopeRequest batchQueryCustomerSaleScopeRequest) {
        List<String> customerCodes = batchQueryCustomerSaleScopeRequest.getCustomerCodes();
        BatchQueryByCustomerCodesRequest customerCodesRequest = BatchQueryByCustomerCodesRequest.builder().customerCodes(customerCodes).build();
        Result<List<CustomerSaleScope>> byCustomerCodes = service.batchQueryByCustomerCodes(customerCodesRequest);
        if (Objects.isNull(customerCodes) || CollectionUtils.isEmpty(byCustomerCodes.getResult())) {
            return Lists.newArrayList();
        }
        List<CustomerSaleScopeSDO> objects = byCustomerCodes.getResult().stream().map(it -> {
            JSONObject jsonObject = JSONObject.parseObject(it.getFeatures());
            String storeHouse = jsonObject.getString("storeHouse");
            CustomerSaleScopeSDO customerSaleScopeSDO = new CustomerSaleScopeSDO();
            BeanUtils.copyProperties(it, customerSaleScopeSDO);
            customerSaleScopeSDO.setStoreHouse(storeHouse);
            return customerSaleScopeSDO;
        }).collect(Collectors.toList());
        return objects;
    }
}
